import { fetcher } from '@/src/utils/fetcher'
import { objectToQueryString } from '@/src/utils/object-to-query-string'
import { cookies } from 'next/headers'
import ProductItem from '../components/product-item'
import { getTranslations } from 'next-intl/server'
import Paginator from '@/src/app/components/paginator'

interface PageProps {
  searchParams: {
    page?: string
    industry?: string
    category?: string
    manufacturer?: string
    model?: string
  }
}

const Page: React.FC<PageProps> = async (props) => {
  const t = await getTranslations()
  const { searchParams } = props
  const cookieStore = cookies()
  const industries = await fetcher<ProductCategory[]>('/api/index/cpFenlei', {
    cookieStore,
  }).then((res) => res.sort((a, b) => a.id - b.id))
  const initialIndustryId = industries[0].id

  const currentPage = searchParams.page ? Number(searchParams.page) : 1
  const industry = searchParams.industry || initialIndustryId.toString()
  const category = searchParams.category !== '0' ? searchParams.category : ''
  const getProductsQuery = () => {
    let productsQuery = {
      page: currentPage.toString(),
      categorypid: industry,
    } as any
    if (category) {
      productsQuery['categoryid'] = category
    }
    if (searchParams.manufacturer) {
      productsQuery['manufacturerid'] = searchParams.manufacturer
    }
    if (searchParams.model) {
      productsQuery['modelid'] = searchParams.model
    }
    return productsQuery
  }
  const products = (await fetcher<WithPaginator<Product>>(
    `/api/index/cpList?${objectToQueryString(getProductsQuery())}`,
    { cookieStore }
  )) || {
    list: [],
    p: 0,
    total: 0,
  }

  if (products.list.length === 0) {
    return (
      <div className='flex justify-center items-center w-full h-[18.75rem] 2xl:h-[28.125rem] text-[#999999] text-[0.875rem] 2xl:text-[1.125rem]'>
        {t('emptyPage')}
      </div>
    )
  }

  return (
    <>
      <div className='grid grid-cols-1 lg:grid-cols-3 gap-4 2xl:gap-6'>
        {products.list.map((product) => {
          return (
            <ProductItem
              key={product.id}
              id={product.id.toString()}
              picture={product.image}
              desc={product.con}
              year={product.year}
              manufacturer={product.manufacturer_name}
              model={product.model_name}
              hours={product.hours}
              category={product.category_name}
              price={product.price}
            />
          )
        })}
      </div>
      <div className='h-[1.875rem] lg:h-[5.875rem] 2xl:h-[8.8125rem]' />
      <Paginator
        initialPage={currentPage}
        total={Math.ceil(products.total / products.p) || 1}
      />
      <div className='h-[2.34475rem] lg:h-[3.5625rem] 2xl:h-[5.34375rem]' />
    </>
  )
}

export default Page
